<?php
namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Log;

class Pay extends Controller
{
    /*
     * 订单类型(price_type)：
     * 1-5 vip类型订单
     * 1001 1002 1003 ... 爵位类型订单
     * 2000 G币专区视频余额支付
     * 支付类型(pay_type)
     * 1.微信支付 2.支付宝支付 3.积分余额支付
     *
     * 注意：vip只赠送积分，爵位直接兑换积分
     * tag 变动积分(全部为正)
     * */

    public function index()
    {
        return 'pay';
    }

    //生成VIP购买订单
    public function create_vip_order()
    {
        if (IS_POST) {
            $user = login_check(true);
            $price_type = input('price_type');
            $pay_type = input('pay_type');

            if (!$price_type || !$pay_type) {
                return json(['code' => 500, 'msg' => '参数错误']);
            }

            $price = Db::table('vo_price')->where('type', $price_type)->cache(false)->find();
            if (!$price) {
                return json(['code' => 500, 'msg' => '支付错误']);
            }

            $now = time();
            $money = $price['price'];
            $memberId = $user['memberId'];

            $orderNo = date('YmdHis', $now);

            if ($pay_type == 1 || $pay_type == 2) { //微信支付、支付宝支付
                $data = [
                    'memberId' => $memberId,
                    'orderNo' => $orderNo,
                    'money' => $money,
                    'pay_type' => $pay_type,
                    'price_type' => $price['id'],
                    'createTime' => $now,
                    'endTime' => $now,
                    'good_num' => 1,
                    'tag' => $price['points'] //充值赠送的积分
                ];

                $res = Db::table('vo_app_order')->insert($data);
                if ($res == 1) {
                    $params = [
                        'partner' => 900745, //商户编号
                        'time' => date('YmdHis', $now),
                        'payoutMemberId' => (string)$memberId,
                        'payoutName' => '小明',
                        'receiptName' => 'CMAX',
                        'produceName' => 'cbox充值',
                        'outTime' => date('YmdHis', $now + 3600), //订单过期时间
                        'produceAmount' => (string)1,
                        'producePrice' => (string)$money,
                        'money' => $this->m($money),
                        'orderNo' => $orderNo,
                        'callbackUrl' => request()->domain() . '/vip_callback',
                        'disburseType' => 1, //即时到账
                        'frostType' => 0, //0-无冻结
                    ];

                    return json(['code' => 200, 'data' => $params]);
                } else {
                    return json(['code' => 500, 'msg' => 'insert error']);
                }
            }

            if ($pay_type == 3) { //走余额支付
                $nobility = Db::table('vo_config')->field('value')->where(['key' => 'nobility'])->find();
                $points_pay = $money * (int)$nobility['value'];

                //扣除剩余的积分
                $user_points = (int)$user['user_points'] - $points_pay;
                if ($user_points < 0) {
                    return json(['code' => 500, 'msg' => '您的G币不足请尽快充值']);
                }

                //加时操作
                $addTime = intval($price['hour']) * 60 * 60;
                $vip_exp_date = strtotime($user['vip_exp_date']);
                if ($vip_exp_date <= time()) {
                    $vip_exp_date_new = date("Y-m-d H:i:s", $addTime + time());
                } else {
                    $vip_exp_date_new = date("Y-m-d H:i:s", $addTime + $vip_exp_date);
                }

                $data = [
                    'memberId' => $memberId,
                    'orderNo' => $orderNo,
                    'money' => 0,
                    'pay_type' => $pay_type,
                    'price_type' => $price['id'],
                    'createTime' => $now,
                    'endTime' => $now,
                    'good_num' => 1,
                    'state' => 1,  //订单状态
                    'vip_exp_date' => $vip_exp_date_new,
                    'tag' => $points_pay //扣除的积分
                ];

                $res = Db::table('vo_app_order')->insert($data);

                if ($res == 1) {
                    //加入积分变动记录
                    $data = [
                        'points_type' => config('points_config')['vip']['type'],
                        'points_change' => -$points_pay,
                        'points_old' => $user['user_points'],
                        'app_user_id' => $user['memberId'],
                        'log_add_time' => date('Y-m-d H:i:s', time())
                    ];

                    Db::table('vo_points_log')->insert($data);

                    //更新用户信息
                    Db::table('vo_app_user')->where('memberId', $memberId)->update([
                        'vip_exp_date' => $vip_exp_date_new,
                        'user_points' => $user_points
                    ]);

                    return json(['code' => 200, 'msg' => "支付成功"]);
                } else {
                    return json(['code' => 500, 'msg' => 'insert error']);
                }
            }
        }
    }

    //生成爵位购买订单
    public function create_nobility_order()
    {
        if (IS_POST) {
            $user = login_check(true);
            $id = input('id');
            $num = input('num');

            $res = Db::table('vo_nobility')->where(['id' => $id])->find();

            $now = time();
            $memberId = $user['memberId'];
            $orderNo = date('YmdHis', $now);
            $points_pay = $res['points'] * $num; //兑换币数
            $money = $res['price'] * $num; //支付金额

            //生成预支付订单
            $data = [
                'memberId' => $memberId,
                'orderNo' => $orderNo,
                'money' => $money,
                'state' => 0,
                'pay_type' => 1,
                'good_num' => $num,
                'price_type' => "100{$id}",
                'createTime' => $now,
                'endTime' => $now,
                'tag' => $points_pay //兑换积分的记录
            ];

            $res = Db::table('vo_app_order')->insert($data);
            if ($res == 1) {
                $params = [
                    'partner' => 900745, //商户编号
                    'time' => date('YmdHis', $now),
                    'payoutMemberId' => (string)$memberId,
                    'payoutName' => '小明',
                    'receiptName' => 'CMAX',
                    'produceName' => 'cbox充值',
                    'outTime' => date('YmdHis', $now + 3600), //订单过期时间
                    'produceAmount' => (string)1,
                    'producePrice' => (string)$money,
                    'money' => $this->m($money),
                    'orderNo' => $orderNo,
                    'callbackUrl' => request()->domain() . '/nobility_callback',
                    'disburseType' => 1, //即时到账
                    'frostType' => 0, //0-无冻结
                ];

                return json(['code' => 200, 'data' => $params]);
            } else {
                return json(['code' => 500, 'msg' => 'insert error']);
            }
        }
    }

    //生成G币专区视频订单
    public function pay_vod_points()
    {
        if (IS_POST) {
            $user = login_check(true);

            $fileId = input('fid');
            if (!$fileId) {
                return json(['code' => 500, 'msg' => '参数错误']);
            }

            $vod = Db::table('vo_video_manage')->where('fileId', $fileId)->find();
            if (!$vod) {
                return json(['code' => 500, 'msg' => '服务器异常']);
            }

            $fileUrl = url_key($vod['fileUrl']);
            $log = Db::table('vo_vod_points_log')->where(['fileId' => $fileId, 'uid' => $user['id']])->find();
            if ($log && strtotime($log['vod_exp_date']) > time()) {
                return json(['code' => 200, 'msg' => "您已支付", "url" => $fileUrl]);
            }

            $now = time();
            $memberId = $user['memberId'];
            $orderNo = date('YmdHis', $now);
            $points_pay = $vod['pay_point'];

            //扣除剩余的积分
            $user_points = (int)$user['user_points'] - $points_pay;
            if ($user_points < 0) {
                return json(['code' => 500, 'msg' => '您的G币不足请尽快充值']);
            }

            $data = [
                'memberId' => $memberId,
                'orderNo' => $orderNo,
                'money' => 0,
                'pay_type' => 3,
                'price_type' => 2000,
                'createTime' => $now,
                'endTime' => $now,
                'good_num' => 1,
                'state' => 1,  //订单状态
                'tag' => $points_pay //扣除的积分
            ];

            $res = Db::table('vo_app_order')->insert($data);
            if ($res == 1) {
                //加入积分变动记录
                $data = [
                    'points_type' => config('points_config')['vod_points']['type'],
                    'points_change' => -$points_pay,
                    'points_old' => $user['user_points'],
                    'app_user_id' => $user['memberId'],
                    'log_add_time' => date('Y-m-d H:i:s', $now)
                ];

                Db::table('vo_points_log')->insert($data);

                //加入视频积分购买日志
                Db::table('vo_vod_points_log')->insert([
                    'fileId' => $fileId,
                    'uid' => $user['id'],
                    'addTime' => date('Y-m-d H:i:s', $now),
                    'vod_exp_date' => date('Y-m-d H:i:s', $now + 86400)
                ]);

                //更新用户信息
                Db::table('vo_app_user')->where('memberId', $memberId)
                    ->update(['user_points' => $user_points]);

                return json(['code' => 200, 'msg' => "支付成功", "url" => $fileUrl, "user_points" => $user_points]);
            } else {
                return json(['code' => 500, 'msg' => 'error']);
            }
        }
    }

    public function nobility_callback()
    {
        $query = file_get_contents("php://input");

        Log::error('nobility_callback:');
        Log::error($query);
        echo 'success';

        //orderNo=20200624104330&
        //payTime=2020-06-24+10%3A44%3A23&
        //disburseTime=20200624104423&
        //cashBalance=0.01&sign=fedf6f1a36f023ed332b5055a2ecec9b&
        //outPayNo=4200000619202006242288003853&disburseNo=CBOX202006241043330741465

        $params = $this->convertUrlQuery($query);
        if (isset($params['orderNo']) && isset($params['cashBalance']) && isset($params['outPayNo'])) {
            $order = Db::table('vo_app_order')->where(['orderNo' => $params['orderNo'], 'state' => 0])->find();
            if ($order) {
                $user = Db::table('vo_app_user')->where('memberId', $order['memberId'])->find();
                if ($user) {
                    $id = str_replace('100', '', $order['price_type']);
                    $res = Db::table('vo_nobility')->where(['id' => $id])->find();
                    $vip_exp_date = strtotime($user['vip_exp_date']);

                    //会员到期时间
                    $addTime = intval($res['hour']) * 60 * 60;
                    if ($vip_exp_date <= time()) {
                        $vip_exp_date_new = date("Y-m-d H:i:s", $addTime + time());
                    } else {
                        $vip_exp_date_new = date("Y-m-d H:i:s", $addTime + $vip_exp_date);
                    }

                    //更新订单状态
                    //微信支付系统的订单号
                    Db::table('vo_app_order')->where('orderNo', $params['orderNo'])->update([
                        'bill_no' => $params['outPayNo'],
                        'state' => 1,
                        'endTime' => time(),
                        'vip_exp_date' => $vip_exp_date_new
                    ]);

                    $points_change = $order['tag'];

                    //加入积分变动记录
                    $data = [
                        'points_type' => config('points_config')['nobility']['type'],
                        'points_change' => $order['tag'],
                        'points_old' => $user['user_points'],
                        'app_user_id' => $user['memberId'],
                        'log_add_time' => date('Y-m-d H:i:s', time())
                    ];

                    Db::table('vo_points_log')->insert($data);

                    $total_amount = $user['total_amount'] + $params['cashBalance'];
                    $user_points = $user['user_points'] + $points_change; //充值赠送的积分

                    //更新用户信息
                    Db::table('vo_app_user')->where('memberId', $order['memberId'])->update([
                        'total_amount' => $total_amount,
                        'user_points' => $user_points,
                        'nobility_exp_date' => $vip_exp_date_new
                    ]);
                }
            }
        }
    }

    public function vip_callback()
    {
        $query = file_get_contents("php://input");
        Log::error('vip_callback:');
        Log::error($query);
        echo 'success';

        $params = $this->convertUrlQuery($query);
        if (isset($params['orderNo']) && isset($params['cashBalance']) && isset($params['outPayNo'])) {

            $order = Db::table('vo_app_order')->where(['orderNo' => $params['orderNo'], 'state' => 0])->find();
            if ($order) {
                $res = Db::table('vo_price')->where('id', $order['price_type'])->find();
                if (strpos($res['type'], 'app_') === 0) {

                    $user = Db::table('vo_app_user')->where('memberId', $order['memberId'])->find();
                    $vip_exp_date = strtotime($user['vip_exp_date']);

                    //会员到期时间
                    $addTime = intval($res['hour']) * 60 * 60;
                    if ($vip_exp_date <= time()) {
                        $vip_exp_date_new = date("Y-m-d H:i:s", $addTime + time());
                    } else {
                        $vip_exp_date_new = date("Y-m-d H:i:s", $addTime + $vip_exp_date);
                    }

                    //更新订单状态
                    Db::table('vo_app_order')->where('orderNo', $params['orderNo'])
                        ->update([
                            'state' => 1,  //订单状态
                            'endTime' => time(),
                            'bill_no' => $params['outPayNo'], //微信支付系统的订单号
                            'vip_exp_date' => $vip_exp_date_new
                        ]);


                    $total_amount = $user['total_amount'] + $params['cashBalance'];
                    $user_points = $user['user_points'] + $order['tag']; //新增充值赠送的积分

                    //加入积分变动记录
                    $data = [
                        'points_type' => config('points_config')['vip']['type'],
                        'points_change' => $order['tag'],
                        'points_old' => $user['user_points'],
                        'app_user_id' => $user['memberId'],
                        'log_add_time' => date('Y-m-d H:i:s', time())
                    ];

                    Db::table('vo_points_log')->insert($data);

                    //更新用户信息
                    Db::table('vo_app_user')->where('memberId', $order['memberId'])->update([
                        'total_amount' => $total_amount,
                        'vip_exp_date' => $vip_exp_date_new,
                        'user_points' => $user_points
                    ]);
                }
            }
        }
    }

    function convertUrlQuery($query)
    {
        $queryParts = explode('&', $query);

        $params = array();
        foreach ($queryParts as $param) {
            $item = explode('=', $param);
            $params[$item[0]] = $item[1];
        }

        return $params;
    }

    function m($money)
    {
        if (true) {
            return $money;
        } else {
            return 0.01;
        }
    }
}
